package com.ten.order.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import com.ten.common.core.entity.EduCourse;
import com.ten.common.core.entity.EduTeacher;
import com.ten.common.core.entity.TOrder;
import com.ten.common.core.entity.TbMember;
import com.ten.common.core.vo.Result;
import com.ten.order.dao.ByUserIdDao;
import com.ten.order.dao.CourseDao;
import com.ten.order.dao.OrderPayDao;
import com.ten.order.dao.TeacherDao;
import com.ten.order.service.OrderPayService;
import com.ten.order.utils.HttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：王薪伟
 * @date ：Created in 2022/12/27 19:48
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class OrderPayServiceImpl implements OrderPayService {

    @Autowired
    private OrderPayDao orderPayDao;

    @Autowired
    private CourseDao courseDao;

    @Autowired
    private TeacherDao teacherDao;

    @Autowired
    private ByUserIdDao userIdDao;

    @Value("${weixin.appid}")
    private String appid;

    @Value("${weixin.mch_id}")
    private String mch_id;

    @Value("${weixin.api_key}")
    private String api_key;

    @Override
    public Result saveOrder(String courseId, String memberId) {

        //查询是否存在该订单
        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        wrapper.eq("member_id", memberId);
        TOrder orders = orderPayDao.selectOne(wrapper);
        if (orders != null) {
            if (orders.getStatus() == 1) {
//                return new Result(5000, "该订单已创建,请先去支付", null);
                return new Result(5000, "该订单支付,无需再付款", null);
            } else {
                try {
                    //调用微信服务器端生成二维码的地址。httpclient的jar的功能。---我再这里已经封装号一个工具类。
                    HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                    httpClient.setHttps(true);
                    //微信接口需要的参数
                    Map<String, String> params = new HashMap<>();
                    params.put("appid", appid);
                    params.put("mch_id", mch_id);
                    params.put("nonce_str", WXPayUtil.generateNonceStr());
                    params.put("body", orders.getCourseTitle());
                    params.put("out_trade_no", orders.getOrderNo());
                    //以分单位order.getPayType()
                    params.put("total_fee", new BigDecimal(0.01).multiply(new BigDecimal(100)).intValue() + "");
                    params.put("spbill_create_ip", "127.0.0.1");//该地址未来应该是你项目部署服务器的ip
                    params.put("notify_url", "http://localhost:8001/order/back");//通知地址
                    params.put("trade_type", "NATIVE");//扫描支付
                    //因为微信接口需要的参数格式为xml格式的字符串。
                    httpClient.setXmlParam(WXPayUtil.generateSignedXml(params, api_key));
                    //执行请求
                    httpClient.post();
//                    System.out.println(orders.getOrderNo() + "++++++++++++++++++++++++++++++++++++++++++++++");

                    //获取请求后响应的结果
                    String content = httpClient.getContent();
//                    System.out.println(content);
                    //把xml格式的字符串转化为map对象
                    Map<String, String> map = WXPayUtil.xmlToMap(content);
                    if ("SUCCESS".equals(map.get("result_code"))) {
                        Map<String, Object> data = new HashMap<>();
                        data.put("code_url", map.get("code_url"));
                        data.put("out_trade_no", orders.getOrderNo());
                        data.put("total_fee", orders.getTotalFee());
                        data.put("course_id", courseId);
                        Result result1 = new Result(2000, "生成二维码成功", data);
                        return result1;
                    }
                    return new Result(5000, "生成二维码失败", null);
                } catch (Exception e) {
                    return new Result(5000, "生成二维码失败", null);
                }
            }
        }

        //2.根据课程编号查询课程详情。并创建订单。
        EduCourse course = courseDao.selectById(courseId);
        //获取讲师信息
        String teacherId = course.getTeacherId();
        QueryWrapper<EduTeacher> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("id", teacherId);
        EduTeacher teacher = teacherDao.selectOne(wrapper2);
        //获取会员信息
        TbMember tbMember = userIdDao.selectById(memberId);

        //创建新的订单
        TOrder order = new TOrder();
        order.setOrderNo(IdUtil.getSnowflakeNextId() + "");//订单号
        order.setCourseId(courseId);
        order.setCourseTitle(course.getTitle());
        order.setCourseCover(course.getCover());
        order.setTeacherName(teacher.getName()); //课程的讲师名称--查询课程时获取。
        order.setMemberId(memberId);
        order.setNickname(tbMember.getNickname());
        order.setMobile(tbMember.getMobile());
        order.setTotalFee(course.getPrice());
        order.setPayType((byte) 0);//支付类型
        order.setStatus((byte) 0);//支付状态
        order.setIsDeleted((byte) 0);//是否删除
        order.setGmtCreate(LocalDateTime.now());
        order.setGmtModified(LocalDateTime.now());
//        System.out.println(order.getOrderNo() + "++++++++++++++++++++++++++++++++++++++++++++++");

        //保存订单
        int row = orderPayDao.insert(order);
        //下单成功
        if (row > 0) {
            try {
                //调用微信服务器端生成二维码的地址。httpclient的jar的功能。---我再这里已经封装号一个工具类。
                HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
                httpClient.setHttps(true);
                //微信接口需要的参数
                Map<String, String> params = new HashMap<>();
                params.put("appid", appid);
                params.put("mch_id", mch_id);
                params.put("nonce_str", WXPayUtil.generateNonceStr());
                params.put("body", order.getCourseTitle());
                params.put("out_trade_no", order.getOrderNo());
                //以分单位order.getPayType()
                params.put("total_fee", new BigDecimal(0.01).multiply(new BigDecimal(100)).intValue() + "");
                params.put("spbill_create_ip", "127.0.0.1");//该地址未来应该是你项目部署服务器的ip
                params.put("notify_url", "http://localhost:8001/order/back");//通知地址
                params.put("trade_type", "NATIVE");//扫描支付
                //因为微信接口需要的参数格式为xml格式的字符串。
                httpClient.setXmlParam(WXPayUtil.generateSignedXml(params, api_key));
                //执行请求
                httpClient.post();

                //获取请求后响应的结果
                String content = httpClient.getContent();
//                System.out.println(content);
                //把xml格式的字符串转化为map对象
                Map<String, String> map = WXPayUtil.xmlToMap(content);
                if ("SUCCESS".equals(map.get("result_code"))) {
                    Map<String, Object> data = new HashMap<>();
                    data.put("code_url", map.get("code_url"));
                    data.put("out_trade_no", order.getOrderNo());
                    data.put("total_fee", order.getTotalFee());
                    data.put("course_id", courseId);
                    Result result1 = new Result(2000, "生成二维码成功", data);
                    return result1;
                }
                return new Result(5000, "生成二维码失败", null);
            } catch (Exception e) {
                return new Result(5000, "生成二维码失败", null);
            }
        } else {
            return new Result(5000, "下单失败", null);
        }
    }

    @Override
    public Result selectStatus(String orderNo) {
//        System.out.println(orderNo + "====================================");
        try {
            //根据订单号远程调用微信的接口 判断当前订单是否支付 httpclient
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            //设置微信接口需要的参数
            Map<String, String> params = new HashMap<>();
            params.put("appid", appid);
            params.put("mch_id", mch_id);
            params.put("out_trade_no", orderNo);
            params.put("nonce_str", WXPayUtil.generateNonceStr());
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(params, api_key));
            //发生请求
            httpClient.post();

            String content = httpClient.getContent();
//            System.out.println(content);
            Map<String, String> map = WXPayUtil.xmlToMap(content);
//            System.out.println(map.get("trade_state"));
            if (map.get("trade_state").equals("SUCCESS")) {
                //1.修改订单的状态。
                TOrder order = new TOrder();
                order.setStatus((byte) 1);
                order.setGmtModified(LocalDateTime.now());
                UpdateWrapper<TOrder> wrapper = new UpdateWrapper<>();
                wrapper.eq("order_no", orderNo);
                orderPayDao.update(order, wrapper);
                //2. 保存支付记录。
                return new Result(2000,"支付成功",null);
            }else if(map.get("trade_state").equals("NOTPAY")){
                return new Result(2001,"未支付请及时                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     支付",null);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return new Result(5000,"订单支付失败",null);
    }
}
